<template>
	<uni-nav-bar dark :fixed="false" shadow background-color="#ff7799" status-bar left-icon="left" left-text="返回"
		title="优惠券信息" @clickLeft="smartBack()" />
	<view style="padding: 8px;">
		<view>
			<view style="position: relative;padding-top: 24rpx;">
				<h2>您的券包</h2>
				<text style="margin-top: 2px;font-size: 13px;color: #888;">筛选类型：{{searchType}}</text>
				<button size="default" type="default" style="color:#fff;backgroundColor:#ff7799;
				borderColor:#ff7799;position: absolute;right: 0;top: 24rpx;height: 36px;line-height: 36px;" hover-class="is-hover"
					@click="showSearchDialog">
					<uni-icons type="settings" size="16" color="#fff"></uni-icons>&nbsp;
					<text style="font-size: 16px;">筛 选</text>
				</button>
				<button size="default" type="default" style=";
				borderColor:#ff7799;position: absolute;right: 160rpx;top: 24rpx;height: 36px;line-height: 36px;"
					hover-class="is-hover" @click="getUserCouponList">
					<uni-icons type="refreshempty" size="16"></uni-icons>&nbsp;
					<text style="font-size: 16px;">重 置</text>
				</button>
			</view>
			<view>
				<template v-if="userCouponList.length > 0">
					<view v-for="(item, index) in userCouponList" :key="item.id" class="draggable-container"
						@touchstart="handleTouchStart(index, $event)" @touchmove="handleTouchMove(index, $event)"
						@touchend="handleTouchEnd(index)"
						:style="{ transform: `translateX(${dragState[index].translateX}px)` }"
						style="overflow: visible;">
						<uni-card :title="item.couponName" :isFull="true" :sub-title="item.couponDescribe"
							:thumbnail="avatar"
							style="margin-top: 10px;background-color: rgba(255,0,0,0.2); position: relative;">
							<!-- 自定义 extra 区域 -->
							<view class="custom-extra">
								<span v-if="item.discountValue<1"><span
										style="font-size: 24px;">{{ item.discountValue * 10 }}</span> 折 </span>
								<span v-else><span style="font-size: 24px;">{{ item.discountValue }}</span> 元 </span>
							</view>

							<!-- 内容区域 -->
							<view class="content-wrapper">
								<view class="main-content">
									<text class="uni-body">{{ item.couponApplicable }}</text>
									<text class="uni-body" v-if="item.expireLeftDays && searchType == '即将到期'"
										style="color: red;">
										&nbsp;&nbsp;&nbsp;仅剩{{ item.expireLeftDays }}天！
									</text>
								</view>
								<text class="uni-body status-text" v-if="item.status!='未使用'">{{ item.status }}</text>
								<text class="uni-body status-text" v-else>
									<button type="default"
										style="font-size: 16px;height: 4vh;color: #fff;background-color: #ffaa00;"
										@click="go2Store(item);"><uni-icons type="gift-filled" size="16"
											color="#fff"></uni-icons> 去使用 <uni-icons type="arrow-right" size="16"
											color="#fff"></uni-icons></button>
								</text>
							</view>
						</uni-card>

						<!-- 删除按钮 -->
						<button v-if="dragState[index].showDeleteBtn" class="delete-btn"
							@click="deleteCoupon(item.id);">
							<uni-icons type="trash" size="24" color="#fff"></uni-icons>
						</button>
					</view>
				</template>

				<!-- 空状态提示 -->
				<view v-else class="empty-state">
					<uni-icons type="wallet" size="40" color="#c0c4cc"></uni-icons>
					<text style="display: block; margin-top: 10px; color: #909399;">流星划过，这里一片虚无~</text>
				</view>
			</view>
		</view>
		<view style="padding-top: 2vh;">
			<view @tap="customToggle">
				<uni-row>
					<uni-col :span="20" offset="1" style="text-align: center;">
						<view class="container">
							<view class="line"></view>
							<text class="title">·
								<uni-icons type="vip" size="16" color="#ffc000"></uni-icons>
								推荐好券 ·
								<text style="font-size: 12px;color: #888;">券后更划算</text>
							</text>
							<view class="line"></view>
						</view>
					</uni-col>
					<uni-col :span="2" style="padding-left: 6px;">
						<uni-icons v-if="customVisible" type="tune-filled" size="18"></uni-icons>
						<uni-icons v-else="customVisible" type="tune" size="18"></uni-icons>
					</uni-col>
				</uni-row>
			</view>
			<template v-if="userAntiCouponList.length > 0">
				<transition name="slide">
					<view v-show="customVisible" class="coupon-list">
						<view v-for="(item, index) in userAntiCouponList" :key="item.id">
							<uni-card :title="item.couponName" :isFull="true" :sub-title="item.describe"
								:thumbnail="avatar"
								style="margin-top: 10px;background-color: rgba(255,165,0,0.2); position: relative;">
								<!-- 自定义 extra 区域 -->
								<view class="custom-extra">
									<span v-if="item.discountValue<1"><span
											style="font-size: 24px;">{{ item.discountValue * 10 }}</span> 折 </span>
									<span v-else><span style="font-size: 24px;">{{ item.discountValue }}</span> 元
									</span>
								</view>

								<!-- 内容区域 -->
								<view class="content-wrapper">
									<view class="main-content">
										<text class="uni-body">{{ item.applicable }}</text>
									</view>
									<text class="uni-body status-text">
										<button type="default"
											style="font-size: 16px;height: 4vh;color: #fff;background-color: #ffaa66;"
											@click="go2Activity(item);"><uni-icons type="fire-filled" size="16"
												color="#f20"></uni-icons> 去抢券 <uni-icons type="arrow-right" size="16"
												color="#fff"></uni-icons></button>
									</text>
								</view>
							</uni-card>
						</view>
					</view>
				</transition>
			</template>

			<!-- 空状态提示 -->
			<view v-else class="empty-state">
				<uni-icons type="info" size="40" color="#c0c4cc"></uni-icons>
				<text style="display: block; margin-top: 10px; color: #909399;">暂无推荐</text>
			</view>
		</view>

		<uni-popup ref="sdVis" type="bottom">
			<view style="background-color: #fff;border-radius: 10px 10px 0 0;max-height: 60vh;width: 100%;float: left;">
				<view class="tabs-container">
					<!-- 选项卡标题 -->
					<scroll-view scroll-x class="tabs-header">
						<view v-for="(tab, index) in tabs" :key="index" class="tab-item"
							:class="{ active: currentIndex === index }" @click="switchTab(index)">
							{{ tab.title }}
						</view>
					</scroll-view>

					<!-- 选项卡内容 -->
					<swiper class="tabs-content" :current="currentIndex" @change="onSwiperChange">
						<swiper-item v-for="(tab, index) in tabs" :key="index">
							<!-- 内容区域留空 -->
							<view class="tab-content" v-if="userConditionCouponSP.length > 0">
								<view v-for="(item,index) in userConditionCouponSP" :key="index" class="card-item"
									@click="handleItemClick(item,index)" :class="{ active: currentItemIndex === index }"
									style="width: 42vw;margin: 1vw;float: left;box-shadow: 2px 2px 2px #ddd;border:1px solid #ddd;border-radius: 25px;">
									<img :src="avatar" style="width: 12vw;margin: 1.5vw;float: left;">
									<text style="width: 20vw;margin: 1.5vw;float: left;">{{ item.title }}</text>
									<text style="width: 20vw;margin: 1.5vw;float: left;color: #888;">{{ item.count }}
										张
									</text>
								</view>
							</view>
							<!-- 空状态提示 -->
							<view v-else class="empty-state">
								<uni-icons type="info" size="40" color="#c0c4cc"></uni-icons>
								<text style="display: block; margin-top: 10px; color: #909399;">未持有此类优惠券</text>
							</view>
						</swiper-item>
					</swiper>
				</view>
				<hr style="opacity: 0.3;">
				<view>
					<button size="default" type="default" class="dialog_ctl_btn" hover-class="is-hover"
						style="border: 1px solid #ddd" @click="closeSearchDialog">取 消
					</button>
					<button size="default" type="primary" class="dialog_ctl_btn" hover-class="is-hover"
						style="background-color: #ff7799;" @click="SearchWithCondition">确 认
					</button>
				</view>
			</view>
		</uni-popup>

	</view>
</template>

<script setup>
	import {
		onMounted,
		ref,
		computed
	} from "vue";
	import {
		getList,
		getAntiList,
		getConditionList,
		getFilter2List,
		autoCheck,
		delteById
	} from "@/api/usercoupon.js";

	const avatar = ref("/assets/imgs/couponIcon.png")
	const customVisible = ref(true);
	const customToggle = () => {
		customVisible.value = !customVisible.value
	}
	const sdVis = ref(null);

	const smartBack = () => {
		const pages = getCurrentPages()
		// 方案1：优先使用原生返回（适合H5/App）
		if (pages.length > 1) {
			uni.navigateBack()
		} else {
			history.length > 1 ? history.back() : uni.reLaunch({
				url: '/pages/index/index'
			})
		}
	}

	const userCouponList = ref([]);
	const userCoupon = ref({});
	const userAntiCouponList = ref([]);
	const userAntiCoupon = ref({});
	const userConditionCouponList = ref([]);
	const userConditionCoupon = ref({});
	const userConditionCouponSP = ref([]);
	const userConditionCouponList2 = ref([]);
	const userConditionCoupon2 = ref({});
	const formData = ref({
		'id': "",
		"userId": "101",
		"type": "",
		"bussinessId": "",
		"applicable": ""
	});
	const searchType = ref('全部');

	const statusFormatter = (it) => {
		switch (it) {
			case 0:
				it = "未使用"
				break;
			case 1:
				it = "已使用"
				break;
			case 2:
				it = "已过期"
				break;
		}
		return it;
	}

	const getUserCouponList = async () => {
		userCouponList.value = [];
		formData.value.type = "";
		formData.value.bussinessId = "";
		formData.value.applicable = "";
		formData.value.id = "";
		searchType.value = '全部';
		let res = await getList(formData.value)
		if (res.code == 200) {
			res.data.forEach(function(item) {
				item.userReceiveCoupon.status = statusFormatter(item.userReceiveCoupon.status)
				userCoupon.value = item.userReceiveCoupon;
				userCoupon.value.couponName = item.coupon.couponName;
				userCoupon.value.couponDescribe = item.coupon.describe;
				userCoupon.value.couponApplicable = item.coupon.applicable;
				userCoupon.value.discountValue = item.coupon.discountValue;
				userCoupon.value.bussinessId = item.coupon.bussinessId;
				userCouponList.value.push(userCoupon.value);
				userCoupon.value = {};
			});
			console.log(userCouponList.value);
			initDragState(userCouponList);
		}
	}

	const autoCheckBefore = async () => {
		let res = await autoCheck()
		if (res.code == 200) {
			getUserCouponList();
		}
	}

	const getUserNotGetList = async () => {
		let res = await getAntiList(formData.value)
		if (res.code == 200) {
			res.data.forEach(function(item) {
				userAntiCoupon.value = item;
				userAntiCouponList.value.push(userAntiCoupon.value);
				userAntiCoupon.value = {};
			});
		}
		console.log(userAntiCouponList.value);
	}

	const showSearchDialog = () => {
		sdVis.value?.open();
		switchTab(0)
		formData.value.type = "代金券"
	}

	const closeSearchDialog = () => {
		sdVis.value?.close();
	}

	// 选项卡数据
	const tabs = [{
			title: '代金券'
		},
		{
			title: '折扣券'
		},
		{
			title: '即将到期'
		}
	];

	// 当前激活的选项卡索引
	const currentIndex = ref(0);

	// 切换选项卡
	const switchTab = (index) => {
		currentIndex.value = index;
		switch (index) {
			case 0:
				formData.value.type = "代金券";
				break;
			case 1:
				formData.value.type = "折扣券";
				break;
			case 2:
				formData.value.type = "up_to_expire";
				break;
		}
		getUserConditionCoupon();
	};

	const getUserConditionCoupon = async () => {
		let res = await getConditionList(formData.value)
		userConditionCouponList.value = [];
		if (res.code == 200) {
			res.data.forEach(function(item) {
				item.userReceiveCoupon.status = statusFormatter(item.userReceiveCoupon.status)
				userConditionCoupon.value = item.userReceiveCoupon;
				userConditionCoupon.value.couponName = item.coupon.couponName;
				userConditionCoupon.value.couponDescribe = item.coupon.describe;
				userConditionCoupon.value.couponApplicable = item.coupon.applicable;
				userCoupon.value.discountValue = item.coupon.discountValue;
				userConditionCoupon.value.bussinessId = item.coupon.bussinessId;
				userConditionCoupon.value.expireLeftDays = item.expireLeftDays;
				userConditionCouponList.value.push(userConditionCoupon.value);
				userConditionCoupon.value = {};
			});
			console.log(userConditionCouponList.value)
			// 数组转换
			const formattedCounts = computed(() => {
				// 第一步：统计属性出现次数
				const countMap = userConditionCouponList.value.reduce((acc, item) => {
					let key = ""
					if (item.couponApplicable == "全场通用") {
						key = item.couponApplicable // 替换为属性名
					} else {
						key = "商家ID: " + item.bussinessId
					}
					acc[key] = (acc[key] || 0) + 1
					return acc
				}, {})
				console.log(countMap);

				// 第二步：转换为指定格式数组
				return Object.entries(countMap).map(([type, count]) => ({
					"title": type,
					"count": count
				}))
			})
			userConditionCouponSP.value = formattedCounts.value
			console.log(userConditionCouponSP.value)
		}
	}

	const currentItemIndex = ref(null);

	const getUserCouponList2 = async () => {
		userCouponList.value = [];
		let res = await getFilter2List(formData.value)
		console.log(res.data);
		if (res.code == 200) {
			res.data.forEach(function(item) {
				item.userReceiveCoupon.status = statusFormatter(item.userReceiveCoupon.status)
				userCoupon.value = item.userReceiveCoupon;
				userCoupon.value.couponName = item.coupon.couponName;
				userCoupon.value.couponDescribe = item.coupon.describe;
				userCoupon.value.couponApplicable = item.coupon.applicable;
				userCoupon.value.discountValue = item.coupon.discountValue;
				userCoupon.value.bussinessId = item.coupon.bussinessId;
				let ed = item.expireLeftDays;
				if (ed < 1 && ed >= 0) {
					userCoupon.value.expireLeftDays = '不到1'
				} else {
					userCoupon.value.expireLeftDays = ed;
				}
				userCouponList.value.push(userCoupon.value);
				userCoupon.value = {};
			});
		}
		console.log(userCouponList.value);
		initDragState(userCouponList);
	}

	// 筛选框点击
	const handleItemClick = (item, index) => {
		formData.value.bussinessId = "";
		formData.value.applicable = "";
		formData.value.id = "";
		currentItemIndex.value = index;
		console.log(item);
		if (item.title != "全场通用") {
			formData.value.bussinessId = item.title.replace("商家ID: ", "");
			formData.value.applicable = "限指定商家";
		} else {
			formData.value.applicable = item.title;
		}
		console.log(formData.value);
	}

	// 确认筛选条件
	const SearchWithCondition = () => {
		closeSearchDialog();
		getUserCouponList2();
		console.log(formData.value.type);
		switch (formData.value.type) {
			case "up_to_expire":
				searchType.value = "即将到期";
				break;
			default:
				searchType.value = formData.value.type;
		}
	}

	// swiper滑动回调
	const onSwiperChange = (e) => {
		currentIndex.value = e.detail.current;
	};

	const dragState = ref([])

	// 初始化拖拽状态
	const initDragState = (list) => {
		list.value.forEach(() => {
			dragState.value.push({
				translateX: 0,
				startX: 0,
				showDeleteBtn: false,
				deleteThreshold: -80 // 删除按钮宽度阈值
			})
		})
	}

	// 触摸事件处理
	const handleTouchStart = (index, event) => {
		// 重置其他卡片状态
		dragState.value.forEach((state, i) => {
			if (i !== index) {
				state.translateX = 0
				state.showDeleteBtn = false
			}
		})

		const touch = event.touches[0]
		dragState.value[index].startX = touch.pageX
		// dragState.value[index].showDeleteBtn = false
	}

	const handleTouchMove = (index, event) => {
		const touch = event.touches[0]
		const moveX = touch.pageX - dragState.value[index].startX
		const newX = dragState.value[index].translateX + moveX

		// 限制最大移动距离（根据删除按钮宽度）
		const maxTranslate = dragState.value[index].deleteThreshold
		dragState.value[index].translateX = Math.max(newX, maxTranslate)
	}

	const handleTouchEnd = (index) => {
		const state = dragState.value[index]
		if (state.translateX <= state.deleteThreshold) {
			state.showDeleteBtn = true
			state.translateX = state.deleteThreshold
		} else {
			// 自动回弹动画
			state.translateX = 0
			state.showDeleteBtn = false
		}
	}

	// 删除操作
	const deleteCoupon = (id) => {
		uni.showModal({
			title: '删除前提示',
			content: '确定要执行删除操作吗？',
			success: (res) => {
				if (res.confirm) {
					console.log('删除优惠券:', id);
					formData.value.id = id;
					deleteOne(id);
				} else if (res.cancel) {
					uni.showToast({
						title: '用户取消操作',
						icon: 'warning'
					})
					const index = userCouponList.value.findIndex(item => item.id === id);
					dragState.value[index].translateX = 0;
					dragState.value[index].showDeleteBtn = false;
				}
			}
		});
	}

	// 封装删除请求
	const deleteOne = async (id) => {
		let res = await delteById(formData.value);
		if (res.code == 200) {
			// 删除后重置状态
			const index = userCouponList.value.findIndex(item => item.id === id);
			if (index > -1) {
				userCouponList.value.splice(index, 1);
				dragState.value[index].translateX = 0;
				dragState.value[index].showDeleteBtn = false;
			}
			uni.showToast({
				title: '删除成功',
				icon: 'success'
			})
		}
	}

	// 使用优惠券，去到附近店铺页面
	const go2Store = (item) => {
		uni.navigateTo({
			url: '/pages/test/store?bussinessId=' + item.bussinessId,
			success: () => console.log('跳转成功'),
			fail: (err) => console.error('跳转失败', err)
		});
	}
	
	const go2Activity = (item) => {
		uni.navigateTo({
			url: '/pages/test/activity?bussinessId=' + item.bussinessId,
			success: () => console.log('跳转成功'),
			fail: (err) => console.error('跳转失败', err)
		});
	}

	onMounted(() => {
		autoCheckBefore();
		getUserNotGetList();
	})
</script>

<style scoped>
	.container {
		display: flex;
		justify-content: center;
		align-items: center;
		gap: 8px;
		/* 控制线与文字的距离 */
	}

	.line {
		width: 14vw;
		/* 控制线的长度 */
		height: 1px;
		/* 控制线的粗细 */
		background-color: #000;
		/* 控制线的颜色 */
	}

	.title {
		color: #000;
		font-style: italic;
	}

	.slide-enter-active,
	.slide-leave-active {
		transition: all 0.5s ease;
	}

	.slide-enter-from {
		transform: translateY(100%);
		opacity: 0;
	}

	.slide-leave-to {
		transform: translateY(100%);
		opacity: 0;
	}

	.dialog_ctl_btn {
		height: 36px;
		line-height: 36px;
		width: 45vw;
		float: left;
		margin: 2vw;
		border-radius: 60px;
	}

	.tabs-container {
		height: 50vh;
		display: flex;
		flex-direction: column;
	}

	.tabs-header {
		white-space: nowrap;
		height: 80rpx;
		line-height: 80rpx;
		border-bottom: 1rpx solid #eee;
	}

	.tab-item {
		display: inline-block;
		padding: 0 30rpx;
		font-size: 28rpx;
		color: #666;
		position: relative;
	}

	.tab-item.active {
		color: #ff7799;
	}

	.tab-item.active::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
		width: 60%;
		height: 4rpx;
		background: #ff7799;
	}

	.tabs-content {
		flex: 1;
	}

	.tab-content {
		padding: 20rpx;
		min-height: 100%;
		background-color: #fff;
	}

	.card-item {
		transition: all 0.3s;
	}

	.card-item.active {
		transform: scale(1.03);
		color: #fff;
		background-color: #ff7799;
	}

	.empty-state {
		text-align: center;
		padding: 40px 0;
		color: #909399;
	}

	.draggable-container {
		position: relative;
		transition: transform 0.3s ease;
		overflow: hidden;
	}

	.delete-btn {
		position: absolute;
		right: -120rpx;
		top: 30px;
		bottom: 0;
		width: 50px;
		height: 50px;
		border-radius: 50%;
		background: #ff4444;
		color: white;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 16px;
		z-index: 1;
	}

	.custom-extra {
		position: absolute;
		right: 20px;
		top: 15px;
		font-weight: bold;
		font-size: 12px;
		font-style: italic;
		color: #ff5a5f;
		/* 可根据需要调整颜色 */
	}

	.content-wrapper {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
	}

	.main-content {
		flex: 1;
	}

	.status-text {
		margin-left: 10px;
		/* 添加一些间距 */
		white-space: nowrap;
		/* 防止文字换行 */
	}

	;
</style>